package com.xyz.service.impl;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.xyz.config.SystemData;
import com.xyz.dto.CountDto;
import com.xyz.dto.HomeLocalDateDto;
import com.xyz.dto.SelectPageAllDto;
import com.xyz.dto.enums.EnumRepState;
import com.xyz.entity.mapper.*;
import com.xyz.entity.pojo.*;
import com.xyz.service.CommonService;
import com.xyz.util.DateUtils;
import com.xyz.util.dto.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;

// 通用业务逻辑
@Service
@Transactional(rollbackFor = Exception.class)
public class CommonServiceImpl implements CommonService {

    @Autowired
    private RepairWorkOrderMapper repairWorkOrderMapper;

    @Autowired
    private SystemEmployeeMapper systemEmployeeMapper;

    @Autowired
    private SystemDirectoryMapper systemDirectoryMapper;

    @Autowired
    private SystemRoleDirectoryMapper systemRoleDirectoryMapper;

    @Autowired
    private SystemDirectoryAppMapper systemDirectoryAppMapper;

    @Autowired
    private SystemRoleDirectoryAppMapper systemRoleDirectoryAppMapper;

    @Autowired
    private SystemDictTypeMapper systemDictTypeMapper;

    @Autowired
    private SystemDictDataMapper systemDictDataMapper;

    @Autowired
    private EquipmentOperationLogMapper equipmentOperationLogMapper;

    @Autowired
    private MessageInfoMapper messageInfoMapper;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private EquipmentInfoMapper equipmentInfoMapper;

    @Autowired
    private EquipmentTreeMapper equipmentTreeMapper;

    @Autowired
    private SystemParameterMapper systemParameterMapper;

    @Override
    public void updateEmployeeMap() throws Exception {
        Map<Long, SystemEmployee> employeeMap = new HashMap<>();
        List<SystemEmployee> systemEmployeeList = systemEmployeeMapper.selectByExample(null);
        for (SystemEmployee systemEmployee : systemEmployeeList) {
            employeeMap.put(systemEmployee.getId(), systemEmployee);
        }
        SystemData.employeeMap = employeeMap;
    }

    @Override
    public List<Map<String, Object>> getDirectory(int type, long roleId) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        if (type == 0 || type == 1) {
            List<SystemDirectory> directoryOneList = new ArrayList<>();
            List<SystemDirectory> directoryTwoList = new ArrayList<>();
            List<SystemDirectory> directoryThreeList = new ArrayList<>();
            Map<String, List<SystemDirectory>> directoryThreeMap = new HashMap<>();
            SystemDirectoryExample sdExample = new SystemDirectoryExample();
            sdExample.setOrderByClause("type , sort ");
            List<SystemDirectory> sdList = systemDirectoryMapper.selectByExample(sdExample);
            for (SystemDirectory sd : sdList) {
                if (sd.getType() == 0) {
                    directoryOneList.add(sd);
                } else if (sd.getType() == 1) {
                    directoryTwoList.add(sd);
                } else if (sd.getType() == 2) {
                    directoryThreeList.add(sd);
                    String baseIdStr = sd.getBaseId().toString();
                    List<SystemDirectory> threeList;
                    if (directoryThreeMap.containsKey(baseIdStr)) {
                        threeList = directoryThreeMap.get(baseIdStr);
                    } else {
                        threeList = new ArrayList<>();
                    }
                    threeList.add(sd);
                    directoryThreeMap.put(baseIdStr, threeList);
                }
            }
            SystemRoleDirectoryExample srdExample = new SystemRoleDirectoryExample();
            srdExample.createCriteria().andRoleIdEqualTo(roleId);
            List<SystemRoleDirectory> srdList = systemRoleDirectoryMapper.selectByExample(srdExample);
            List<Long> userDirectoryIdList = new ArrayList<>();
            for (SystemRoleDirectory srd : srdList) {
                userDirectoryIdList.add(srd.getDirectoryId());
            }
            if (type == 0) {  // PC登录时返回权限
                if (userDirectoryIdList.size() == 0) {
                    return list;
                }
                for (SystemDirectory sdOne : directoryOneList) {
                    if (userDirectoryIdList.contains(sdOne.getId())) {
                        Map<String, Object> oneMap = new HashMap<>();
                        oneMap.put("id", sdOne.getId());
                        oneMap.put("name", sdOne.getMark());
                        oneMap.put("title", sdOne.getTitle());
                        oneMap.put("index", sdOne.getSort());
                        List<Map<String, Object>> towList = new ArrayList<>();
                        for (SystemDirectory sdTwo : directoryTwoList) {
                            if (sdTwo.getBaseId().equals(sdOne.getId()) && userDirectoryIdList.contains(sdTwo.getId())) {
                                List<String> roleList = new ArrayList<>();
                                List<SystemDirectory> threeList = directoryThreeMap.getOrDefault(sdTwo.getId().toString(), new ArrayList<>());
                                for (SystemDirectory threeSd : threeList) {
                                    if (userDirectoryIdList.contains(threeSd.getId())) {
                                        roleList.add(threeSd.getMark());
                                    }
                                }
                                Map<String, Object> twoMap = new HashMap<>();
                                twoMap.put("id", sdTwo.getId());
                                twoMap.put("name", sdTwo.getMark());
                                twoMap.put("title", sdTwo.getTitle());
                                twoMap.put("role", roleList);
                                twoMap.put("index", sdTwo.getSort());
                                towList.add(twoMap);
                            }
                        }
                        oneMap.put("children", towList);
                        list.add(oneMap);
                    }
                }
            } else {  // PC角色分配权限
                for (SystemDirectory sdOne : directoryOneList) {
                    Map<String, Object> oneMap = new HashMap<>();
                    oneMap.put("id", sdOne.getId());
                    oneMap.put("name", sdOne.getMark());
                    oneMap.put("title", sdOne.getTitle());
                    oneMap.put("index", sdOne.getSort());
                    oneMap.put("check", userDirectoryIdList.contains(sdOne.getId()));
                    List<Map<String, Object>> towList = new ArrayList<>();
                    for (SystemDirectory sdTwo : directoryTwoList) {
                        if (sdTwo.getBaseId().equals(sdOne.getId())) {
                            Map<String, Object> twoMap = new HashMap<>();
                            twoMap.put("id", sdTwo.getId());
                            twoMap.put("name", sdTwo.getMark());
                            twoMap.put("title", sdTwo.getTitle());
                            twoMap.put("index", sdTwo.getSort());
                            twoMap.put("check", userDirectoryIdList.contains(sdTwo.getId()));
                            List<Map<String, Object>> threeList = new ArrayList<>();
                            for (SystemDirectory sdThree : directoryThreeList) {
                                if (sdThree.getBaseId().equals(sdTwo.getId())) {
                                    Map<String, Object> threeMap = new HashMap<>();
                                    threeMap.put("id", sdThree.getId());
                                    threeMap.put("name", sdThree.getMark());
                                    threeMap.put("title", sdThree.getTitle());
                                    threeMap.put("index", sdThree.getSort());
                                    threeMap.put("check", userDirectoryIdList.contains(sdThree.getId()));
                                    threeList.add(threeMap);
                                }
                            }
                            twoMap.put("children", threeList);
                            towList.add(twoMap);
                        }
                    }
                    oneMap.put("children", towList);
                    list.add(oneMap);
                }
            }
        } else {
            List<SystemDirectoryApp> directoryOneList = new ArrayList<>();
            List<SystemDirectoryApp> directoryTwoList = new ArrayList<>();
            SystemDirectoryAppExample sdaExample = new SystemDirectoryAppExample();
            sdaExample.setOrderByClause("type , sort ");
            List<SystemDirectoryApp> sdaList = systemDirectoryAppMapper.selectByExample(sdaExample);
            for (SystemDirectoryApp sda : sdaList) {
                if (sda.getType() == 0) {
                    directoryOneList.add(sda);
                } else {
                    directoryTwoList.add(sda);
                }
            }

            SystemRoleDirectoryAppExample srdaExample = new SystemRoleDirectoryAppExample();
            srdaExample.createCriteria().andRoleIdEqualTo(roleId);
            List<SystemRoleDirectoryApp> srdaList = systemRoleDirectoryAppMapper.selectByExample(srdaExample);
            List<Long> userDirectoryIdList = new ArrayList<>();
            for (SystemRoleDirectoryApp srda : srdaList) {
                userDirectoryIdList.add(srda.getDirectoryId());
            }

            if (type == 2) {  // APP登录时返回权限
                if (userDirectoryIdList.size() == 0) {
                    return list;
                }
                for (SystemDirectoryApp sdaOne : directoryOneList) {
                    if (userDirectoryIdList.contains(sdaOne.getId())) {
                        Map<String, Object> oneMap = new HashMap<>();
                        oneMap.put("id", sdaOne.getId());
                        oneMap.put("name", sdaOne.getMark());
                        oneMap.put("title", sdaOne.getTitle());
                        oneMap.put("index", sdaOne.getIndex());

                        List<Map<String, Object>> towList = new ArrayList<>();
                        for (SystemDirectoryApp sdaTwo : directoryTwoList) {
                            if (sdaTwo.getBaseId().equals(sdaOne.getId()) && userDirectoryIdList.contains(sdaTwo.getId())) {
                                Map<String, Object> twoMap = new HashMap<>();
                                twoMap.put("id", sdaTwo.getId());
                                twoMap.put("name", sdaTwo.getMark());
                                twoMap.put("title", sdaTwo.getTitle());
                                twoMap.put("index", sdaTwo.getIndex());
                                towList.add(twoMap);
                            }
                        }
                        oneMap.put("children", towList);
                        list.add(oneMap);
                    }
                }
            } else {  // APP角色分配权限
                for (SystemDirectoryApp sdaOne : directoryOneList) {
                    Map<String, Object> oneMap = new HashMap<>();
                    oneMap.put("id", sdaOne.getId());
                    oneMap.put("name", sdaOne.getMark());
                    oneMap.put("title", sdaOne.getTitle());
                    oneMap.put("index", sdaOne.getIndex());
                    oneMap.put("check", userDirectoryIdList.contains(sdaOne.getId()));
                    List<Map<String, Object>> towList = new ArrayList<>();
                    for (SystemDirectoryApp sdaTwo : directoryTwoList) {
                        if (sdaTwo.getBaseId().equals(sdaOne.getId())) {
                            Map<String, Object> twoMap = new HashMap<>();
                            twoMap.put("id", sdaTwo.getId());
                            twoMap.put("name", sdaTwo.getMark());
                            twoMap.put("title", sdaTwo.getTitle());
                            twoMap.put("index", sdaTwo.getIndex());
                            twoMap.put("check", userDirectoryIdList.contains(sdaTwo.getId()));
                            towList.add(twoMap);
                        }
                    }
                    oneMap.put("children", towList);
                    list.add(oneMap);
                }
            }
        }
        return list;
    }

    @Override
    public Map<Integer, String> getDictMap(String... dictTypeCode) throws Exception {
        Map<Integer, String> dictMap = new HashMap<>();
        SystemDictTypeExample sdtExample = new SystemDictTypeExample();
        sdtExample.createCriteria().andDictTypeCodeIn(Arrays.asList(dictTypeCode));
        List<SystemDictType> sdtList = systemDictTypeMapper.selectByExample(sdtExample);
        for (SystemDictType sdt : sdtList) {
            SystemDictDataExample sddExample = new SystemDictDataExample();
            sddExample.createCriteria().andDictTypeIdEqualTo(sdt.getId());
            List<SystemDictData> sddList = systemDictDataMapper.selectByExample(sddExample);
            for (SystemDictData sdd : sddList) {
                dictMap.put(sdd.getDictValue(), sdd.getDictName());
            }
        }
        return dictMap;
    }

    @Override
    public HomeLocalDateDto selectCountTime(CountDto countDto) throws Exception {
        HomeLocalDateDto dto = new HomeLocalDateDto();
        int timeNum = 0;
        if (StrUtil.isNotBlank(countDto.getTimeNum())) {
            timeNum = Integer.parseInt(countDto.getTimeNum());
        }
        LocalTime min = LocalTime.MIN;
        LocalTime max = LocalTime.MAX;
        LocalDate firstDayOfMonth = null;
        LocalDate lastDayOfMonth = null;
        // 1：月份,2：季度,3：年份,4：自定义
        if ("1".equals(countDto.getType())) {
            int year = DateUtil.thisYear();
            firstDayOfMonth = LocalDate.of(year, timeNum, 1);
            lastDayOfMonth = firstDayOfMonth.withDayOfMonth(firstDayOfMonth.lengthOfMonth());
        } else if ("2".equals(countDto.getType())) {
            int year = DateUtil.thisYear();
            //季度开始时间
            firstDayOfMonth = LocalDate.of(year, timeNum*3-2, 1);
            //季度结束时间月第一天
            LocalDate firstDayOfMonth2 = LocalDate.of(year, timeNum*3, 1);
            //季度结束时间
            lastDayOfMonth = firstDayOfMonth2.withDayOfMonth(firstDayOfMonth2.lengthOfMonth());
        } else if ("3".equals(countDto.getType())) {
            firstDayOfMonth = LocalDate.of(timeNum, 1, 1);
            lastDayOfMonth = firstDayOfMonth.withDayOfYear(firstDayOfMonth.lengthOfYear());
        } else if ("4".equals(countDto.getType())) {
            firstDayOfMonth = LocalDateTimeUtil.parseDate(countDto.getStartTime(),"yyyy-MM-dd");
            lastDayOfMonth = LocalDateTimeUtil.parseDate(countDto.getEndTime(),"yyyy-MM-dd");
        }
        if(firstDayOfMonth != null){
            dto.setFirstDay(firstDayOfMonth);
            dto.setLastDay(lastDayOfMonth);
            dto.setStartTime(Date.from(firstDayOfMonth.atTime(min).atZone(ZoneId.systemDefault()).toInstant()));
            dto.setEndTime(Date.from(lastDayOfMonth.atTime(max).atZone(ZoneId.systemDefault()).toInstant()));
        }
        return dto;
    }

    @Override
    public List<Long> selectManagerUserIdList(int type) throws Exception {
        SystemUserExample suExample = new SystemUserExample();
        suExample.createCriteria().andRoleIdEqualTo((long) (100000 + type)).andIsDeleteEqualTo(0);
        List<SystemUser> suList = systemUserMapper.selectByExample(suExample);
        return CollStreamUtil.toList(suList, SystemUser::getId);
    }

    @Override
    public void insertMessageInform(long userId, String title, String content, int businessType, int businessGroup, Long businessId, String businessCode) throws Exception {
        MessageInfo newMi = new MessageInfo();
        newMi.setUserId(userId);
        newMi.setMessageType(1);
        newMi.setTitle(title);
        newMi.setContent(content);
        newMi.setState(1);
        newMi.setBusinessType(businessType);
        newMi.setBusinessGroup(businessGroup);
        newMi.setBusinessId(businessId);
        newMi.setBusinessCode(businessCode);
        newMi.setCreateTime(new Date());
        messageInfoMapper.insert(newMi);
    }

    @Override
    public void insertMessageBacklog(long userId, String title, String content, int businessType, int businessGroup, Long businessId, String businessCode) throws Exception {
        MessageInfo newMi = new MessageInfo();
        newMi.setUserId(userId);
        newMi.setMessageType(2);
        newMi.setTitle(title);
        newMi.setContent(content);
        newMi.setState(1);
        newMi.setBusinessType(businessType);
        newMi.setBusinessGroup(businessGroup);
        newMi.setBusinessId(businessId);
        newMi.setBusinessCode(businessCode);
        newMi.setCreateTime(new Date());
        messageInfoMapper.insert(newMi);
    }

    @Override
    public void insertEquipmentOperationLog(long emId, long employeeId, String operation) throws Exception {
        EquipmentOperationLog newEol = new EquipmentOperationLog();
        newEol.setEmId(emId);
        newEol.setEmployeeId(employeeId);
        newEol.setOperation(operation);
        newEol.setOperationTime(new Date());
        equipmentOperationLogMapper.insert(newEol);
    }

    /*
     * 根据登录权限获取对应的维修单数据
     * */
    @Override
    public List<RepairWorkOrder> getRepairWorkOrderAll(LoginInfo loginInfo, SelectPageAllDto selectPageAllDto) throws Exception {
        String employeeName = loginInfo.getLoginEmployeeName();
        RepairWorkOrderExample tExample = new RepairWorkOrderExample();
        RepairWorkOrderExample.Criteria repCriteria = tExample.createCriteria();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (StrUtil.isNotEmpty(selectPageAllDto.getRepState())) {
            repCriteria.andRepStateEqualTo(Integer.parseInt(selectPageAllDto.getRepState()));
            /*if (EnumRepState.PENDING_RECEIVE.getRepState() == Integer.parseInt(selectPageAllDto.getRepState())) {
                List<Integer> stateIn = new ArrayList<>();
                stateIn.add(EnumRepState.PENDING_RECEIVE.getRepState());
                stateIn.add(EnumRepState.PENDING_REFUSE.getRepState());
                stateIn.add(EnumRepState.PENDING_TRANSFER.getRepState());
                repCriteria.andRepStateIn(stateIn);
            } else {
                repCriteria.andRepStateEqualTo(Integer.parseInt(selectPageAllDto.getRepState()));
            }*/
        }

        if (StrUtil.isNotEmpty(selectPageAllDto.getUrgencyLevel())) {
            repCriteria.andUrgencyLevelEqualTo(Integer.parseInt(selectPageAllDto.getUrgencyLevel()));
        }

        if (StrUtil.isNotEmpty(selectPageAllDto.getWorkOrderCode())) {
            repCriteria.andWorkOrderCodeLike("%" + selectPageAllDto.getWorkOrderCode() + "%");
        }
        if (StrUtil.isNotEmpty(selectPageAllDto.getStartTime())) {
            repCriteria.andCreateTimeGreaterThanOrEqualTo(sdf.parse(selectPageAllDto.getStartTime()));
        }

        if (StrUtil.isNotEmpty(selectPageAllDto.getEndTime())) {
            repCriteria.andCreateTimeLessThanOrEqualTo(sdf.parse(selectPageAllDto.getEndTime()));
        }
        //维修状态
        if (StrUtil.isNotEmpty(selectPageAllDto.getRepState())) {
            repCriteria.andRepStateEqualTo(Integer.parseInt(selectPageAllDto.getRepState()));
        }
        SimpleDateFormat sdfStart = new SimpleDateFormat("yyyy-MM-dd 00:00:00.000");
        SimpleDateFormat sdfEnd = new SimpleDateFormat("yyyy-MM-dd 23:59:59.999");
        // 新增 维修完成结束时间 条件
        if (StrUtil.isNotEmpty(selectPageAllDto.getRepStartTime())) {
            Date repStartTime = DateUtils.createDate(selectPageAllDto.getRepStartTime(), "23:59:59.999");
//            // 将前端传来的日期字符串解析为 Date 类型
//            Date repStartDate = sdf.parse(selectPageAllDto.getRepStartTime());
//            // 将 Date 类型格式化为所需的 datetime 格式
//            String formattedStartDate = sdfEnd.format(repStartDate);
//            Date repStartTime = sdfEnd.parse(formattedStartDate);
            // 设置 rep_start_time 小于等于条件
            repCriteria.andRepStartTimeLessThanOrEqualTo(repStartTime);
        }
        // 新增 维修完成开始时间 条件
        if (StrUtil.isNotEmpty(selectPageAllDto.getRepTime())) {
            Date repTime = DateUtils.createDate(selectPageAllDto.getRepTime(), "00:00:00.000");
//            // 将前端传来的日期字符串解析为 Date 类型
//            Date repDate = sdf.parse(selectPageAllDto.getRepTime());
//            // 将 Date 类型格式化为所需的 datetime 格式
//            String formattedDate = sdfStart.format(repDate);
//            Date repTime = sdfStart.parse(formattedDate);
            // 设置 rep_start_time 大于等于条件
            repCriteria.andRepTimeGreaterThanOrEqualTo(repTime);
        }
        tExample.setOrderByClause("create_time desc");
        List<RepairWorkOrder> repairList = repairWorkOrderMapper.selectByExample(tExample);
        return repairList;
    }


    /*
     * APP根据状态查询对应数据
     * */
    @Override
    public List<RepairWorkOrder> getAppRepairWorkOrderAll(LoginInfo loginInfo, SelectPageAllDto selectPageAllDto) throws Exception {
        //List<String> loginRoleDirectoryMarkList = loginInfo.getLoginRoleDirectoryMarkList();

        RepairWorkOrderExample tExample = new RepairWorkOrderExample();
        RepairWorkOrderExample.Criteria repCriteria = tExample.createCriteria();

        int state = Integer.parseInt(selectPageAllDto.getRepState());
        subRepCriteria1(selectPageAllDto, repCriteria);
        if (EnumRepState.PENDING_ANNOUNCE.getRepState() == state) {
            /*if (!loginRoleDirectoryMarkList.contains(SystemData.PAGE_REP_PENDING_ANNOUNCE)) {
                //有权限才展示数据
                return new ArrayList<>();
            }*/
            repCriteria.andRepStateEqualTo(state);
        } else if (EnumRepState.PENDING_RECEIVE.getRepState() == state) {
            /*if (!loginRoleDirectoryMarkList.contains(SystemData.PAGE_REP_ORDER_GRABBING)) {
                //有权限才展示数据
                return new ArrayList<>();
            }*/
            repCriteria.andRepStateEqualTo(state);
        } else if (EnumRepState.PENDING_REFUSE.getRepState() == state) {
            /*if (!loginRoleDirectoryMarkList.contains(SystemData.PAGE_REP_DISPATCH)) {
                //有权限才展示数据
                return new ArrayList<>();
            }*/
            List<Integer> stateIn = new ArrayList<>();
            stateIn.add(EnumRepState.PENDING_RECEIVE.getRepState());
            stateIn.add(EnumRepState.PENDING_REFUSE.getRepState());
            stateIn.add(EnumRepState.PENDING_TRANSFER.getRepState());
            repCriteria.andRepStateIn(stateIn);
        } else if (EnumRepState.ACCEPTED_NO.getRepState() == state) {
            /*if (!loginRoleDirectoryMarkList.contains(SystemData.PAGE_REP_ACCEPT_ASSIG)) {
                //有权限才展示数据
                return new ArrayList<>();
            }*/
            repCriteria.andRepStateEqualTo(state);
        } else if (EnumRepState.ACCEPTED_YES.getRepState() == state) {
            /*if (!loginRoleDirectoryMarkList.contains(SystemData.PAGE_REP_ACCEPT)) {
                //有权限才展示数据
                return new ArrayList<>();
            }*/
            repCriteria.andRepStateEqualTo(state);
            repCriteria.andAcceptEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
        } else if (EnumRepState.ALLOCATED.getRepState() == state) {
            /*if (!loginRoleDirectoryMarkList.contains(SystemData.PAGE_REP_I_HANDLE)) {
                //有权限才展示数据
                return new ArrayList<>();
            }*/
            List<Integer> stateIn = new ArrayList<>();
            stateIn.add(EnumRepState.ALLOCATED.getRepState());
            stateIn.add(EnumRepState.UNDE_REPAIR.getRepState());
            stateIn.add(EnumRepState.SUSPEND_REPAIR.getRepState());
            repCriteria.andRepStateIn(stateIn);
            repCriteria.andMaintenEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
        } else if (EnumRepState.MAINTENANCE_YES.getRepState() == state) {
            /*if (!loginRoleDirectoryMarkList.contains(SystemData.PAGE_REP_HISTORY)) {
                //有权限才展示数据
                return new ArrayList<>();
            }*/
            List<Integer> stateIn = new ArrayList<>();
            stateIn.add(EnumRepState.INVALID.getRepState());
            stateIn.add(EnumRepState.MAINTENANCE_YES.getRepState());
            repCriteria.andRepStateIn(stateIn);
            repCriteria.andEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
            RepairWorkOrderExample.Criteria repCriteria2 = tExample.or();
            subRepCriteria1(selectPageAllDto, repCriteria2);
            repCriteria2.andRepStateIn(stateIn);
            repCriteria2.andAnnounceEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
            RepairWorkOrderExample.Criteria repCriteria3 = tExample.or();
            subRepCriteria1(selectPageAllDto, repCriteria3);
            repCriteria3.andRepStateEqualTo(EnumRepState.MAINTENANCE_YES.getRepState());
            repCriteria3.andMaintenEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
            RepairWorkOrderExample.Criteria repCriteria4 = tExample.or();
            subRepCriteria1(selectPageAllDto, repCriteria4);
            repCriteria4.andRepStateEqualTo(EnumRepState.MAINTENANCE_YES.getRepState());
            repCriteria4.andAcceptEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
        }
        tExample.setOrderByClause("create_time desc");
        List<RepairWorkOrder> repairList = repairWorkOrderMapper.selectByExample(tExample);
        return repairList;
    }

    private void subRepCriteria1(SelectPageAllDto selectPageAllDto, RepairWorkOrderExample.Criteria repCriteria) throws Exception {
        if (StrUtil.isNotEmpty(selectPageAllDto.getUrgencyLevel())) {
            repCriteria.andUrgencyLevelEqualTo(Integer.parseInt(selectPageAllDto.getUrgencyLevel()));
        }

        if (StrUtil.isNotEmpty(selectPageAllDto.getWorkOrderCode())) {
            repCriteria.andWorkOrderCodeLike("%" + selectPageAllDto.getWorkOrderCode() + "%");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (StrUtil.isNotEmpty(selectPageAllDto.getStartTime())) {
            repCriteria.andCreateTimeGreaterThanOrEqualTo(sdf.parse(selectPageAllDto.getStartTime()));
        }

        if (StrUtil.isNotEmpty(selectPageAllDto.getEndTime())) {
            repCriteria.andCreateTimeLessThanOrEqualTo(sdf.parse(selectPageAllDto.getEndTime()));
        }
    }

    /*
     * 根据员工ID获取员工名称公共方法
     * */
    @Override
    public String getEmployeeNameById(Long employeeId) {
        SystemEmployee systemEmployee = SystemData.employeeMap.get(employeeId);
        if (systemEmployee == null) {
            return "";
        }
        return systemEmployee.getEmployeeName();
    }

    @Override
    public List<SystemDictData> getSysDateListByCode(String dictTypeCode) {
        SystemDictTypeExample sdtExample = new SystemDictTypeExample();
        sdtExample.createCriteria().andDictTypeCodeEqualTo(dictTypeCode);
        List<SystemDictType> sdtList = systemDictTypeMapper.selectByExample(sdtExample);
        if (CollUtil.isNotEmpty(sdtList)) {
            SystemDictDataExample sddExample = new SystemDictDataExample();
            sddExample.createCriteria().andDictTypeIdEqualTo(sdtList.get(0).getId());
            sddExample.setOrderByClause("dict_sort");
            return systemDictDataMapper.selectByExample(sddExample);
        }
        return new ArrayList<>();
    }

    /*
    * 根据设备ID获取子系统树
    * */
    @Override
    public EquipmentTree getTree2ByEmId(Long emId) {
        EquipmentInfo equipmentInfo = equipmentInfoMapper.selectByPrimaryKey(emId);
        if(equipmentInfo != null){
            Long emTree = equipmentInfo.getSubTreeId();
            EquipmentTree equipmentTree = equipmentTreeMapper.selectByPrimaryKey(emTree);
            if(equipmentTree.getType() == 2){
                return equipmentTree;
            }
        }
        return null;
    }

    @Override
    public Map<Long, EquipmentTree> getEquipmentTreeMap() {
        EquipmentTreeExample example = new EquipmentTreeExample();
        EquipmentTreeExample.Criteria criteria = example.createCriteria();
        criteria.andTypeNotEqualTo(3);
        List<EquipmentTree> equipmentTrees = equipmentTreeMapper.selectByExample(example);
        Map<Long,EquipmentTree> treeMap = new HashMap<>();
        equipmentTrees.forEach(t -> treeMap.put(t.getId(), t));
        return treeMap;
    }

    /*
    * 根据子系统获取区域名称
    * */
    @Override
    public String getTreeStrById(Map<Long, EquipmentTree> treeMap, Long treeId) {
        String locat = "";
        EquipmentTree equipmentTree2 = treeMap.get(treeId);
        if(equipmentTree2 != null){
            EquipmentTree equipmentTree1 = treeMap.get(equipmentTree2.getBaseId());
            if(equipmentTree1 != null){
                EquipmentTree equipmentTree = treeMap.get(equipmentTree1.getBaseId());
                if(equipmentTree != null){
                    locat = equipmentTree.getName();
                }
            }
        }
        return locat;
    }

    @Override
    public String getBxWorkOrderCode() {
        String key = SystemData.UPKEEP_WORK_NUMBER;
        String format = DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMATTER);
        SystemParameter sp = systemParameterMapper.selectByPrimaryKey(key);
        int num = Integer.parseInt(sp.getParameterValue()) + 1;
        String code;
        if (num < 10) {
            code = "000" + num;
        } else if (num < 100) {
            code = "00" + num;
        } else if (num < 1000) {
            code = "0" + num;
        } else {
            code = "" + num;
        }
        sp.setParameterValue(num + "");
        systemParameterMapper.updateByPrimaryKey(sp);
        return "wb" + format + code;
    }

    @Override
    public String getPatrolCode() {
        Date currentDate = new Date();
        String format = DateUtil.format(currentDate, DatePattern.PURE_DATE_FORMATTER);
        SystemParameter sp = systemParameterMapper.selectByPrimaryKey(SystemData.PATROL_WORK_NUMBER);
        int num = Integer.parseInt(sp.getParameterValue()) + 1;
        String code;
        if (num < 10) {
            code = "000" + num;
        } else if (num < 100) {
            code = "00" + num;
        } else if (num < 1000) {
            code = "0" + num;
        } else {
            code = "" + num;
        }
        sp.setParameterValue(num + "");
        systemParameterMapper.updateByPrimaryKey(sp);
        return "XJ" + format + code;
    }

}
